//
// joinGame.cpp for joinGame in /home/taitai/rtyperoxxor/serveur
// 
// Made by yannis berrouag
// Login   <berrou_y@epitech.net>
// 
// Started on  Fri Jan 13 14:36:49 2012 yannis berrouag
// Last update Sat Jan 14 17:23:00 2012 yannis berrouag
//

#include "joinGame.h"

std::string     inttostring(int nb)
{
  std::string result;
  std::ostringstream out;
  out << nb;
  result = out.str();
  return result;
}

void    joinGame::onCall(Player *player, std::string const &name, void *data, unsigned int id, protocol::NetHeader *header) {
  gamePool	*instance = gamePool::getInstance();
  std::cout << "map : " << instance->getMap().size() << std::endl;
  if (!this->join(instance, player))
    {
      this->createGame(instance, player);
    }
  std::cout << "map : " << instance->getMap().size() << std::endl;
  std::string ret = inttostring(portId);
  player->getProto()->send(player, protocol::GAME_PORT, name, ret.c_str(), ret.size(), id);
  // envoyer un paquet pour dire au client de se co en udp
}

bool	joinGame::join(gamePool *instance, Player *player)
{
  std::map<int, gameThread *>::iterator	it;

  if (instance->getMap().size() == 0)
    return false;
  for (it = instance->getMap().begin(); it != instance->getMap().end(); ++it)
    {
      if ((*it).second->isLocked() == false)
	{
	  if ((*it).second->getNbPlayers() < 4)
	    {
	      (*it).second->addPlayers(player);
	      player->setAway(true);
	      return true;
	    }
	}
    }
  return false;
}

void	joinGame::createGame(gamePool *instance, Player *player)
{
  gameThread	*newGame = new gameThread();
  

  newGame->addPlayers(player);
  instance->addToMap(newGame, incId);
  player->setAway(true);
}
